package com.zxjbyte.yiyi.framework.web.handler;

import cn.hutool.core.util.StrUtil;
import com.zxjbyte.yiyi.framework.common.constant.StringPool;
import com.zxjbyte.yiyi.framework.common.domain.api.R;
import com.zxjbyte.yiyi.framework.common.domain.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.Servlet;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常处理，处理可预见的异常，Order 排序优先级高
 * @Author zhangxingjia
 * @Date 2023/3/7 16:46
 * @Version: 1.0
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) //servlet运行环境生效
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 SpringMVC 请求参数缺失
     * @param ex
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleError(MissingServletRequestParameterException ex) {
        log.warn("[MissingServletRequestParameterException] {}", ex.getMessage());
        String message = String.format("缺少必要的请求参数 [缺少参数: %s]", ex.getParameterName());
        return R.fail(ResultCode.PARAM_MISS, message);
    }

    /**
     * 处理 SpringMVC 请求参数类型错误
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleError(MethodArgumentTypeMismatchException ex) {
        log.warn("[MethodArgumentTypeMismatchException] {}", ex.getMessage());
        String message = String.format("请求参数格式错误 [错误参数: %s]", ex.getName());
        return R.fail(ResultCode.PARAM_TYPE_ERROR, message);
    }

    /**
     * 处理 SpringMVC 参数校验不正确
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleError(MethodArgumentNotValidException ex) {
        log.warn("[MethodArgumentNotValidException] {}", ex.getMessage());
        return handleError(ex.getBindingResult());
    }

    /**
     * 处理 SpringMVC 参数绑定不正确，本质上也是通过 Validator 校验
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleError(BindException ex) {
        log.warn("[BindException] {}", ex.getMessage());
        return handleError(ex.getBindingResult());
    }

    private R<Void> handleError(BindingResult result) {
        FieldError error = result.getFieldError();
        assert error != null; // 断言，避免告警
        return R.fail(ResultCode.PARAM_BIND_ERROR, error.getDefaultMessage());
    }

    /**
     * 处理 Validator 校验不通过产生的异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleError(ConstraintViolationException ex) {
        log.warn("[ConstraintViolationException] {}", ex.getMessage());
        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName();
        String message = String.format("%s: %s", path, violation.getMessage());
        return R.fail(ResultCode.PARAM_VALID_ERROR, message);
    }

    /**
     * 处理 SpringMVC 请求地址不存在
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public R<Void> handleError(NoHandlerFoundException ex) {
        log.warn("[NoHandlerFoundException] {}", ex.getMessage());
        return R.fail(ResultCode.NOT_FOUND, ex.getMessage());
    }

    /**
     * 处理 SpringMVC 请求方法不正确
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public R<Void> handleError(HttpRequestMethodNotSupportedException ex) {
        log.warn("[HttpRequestMethodNotSupportedException] {}", ex.getMessage());
        return R.fail(ResultCode.METHOD_NOT_SUPPORTED, ex.getMessage());
    }

    /**
     * 消息不能读取
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R<Void> handleError(HttpMessageNotReadableException ex) {
        log.warn("[HttpMessageNotReadableException] {}", ex.getMessage());
        return R.fail(ResultCode.MSG_NOT_READABLE, ex.getMessage());
    }

    /**
     * 不支持当前媒体类型
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public R<Void> handleError(HttpMediaTypeNotSupportedException ex) {
        log.warn("[HttpMediaTypeNotSupportedException] {}", ex.getMessage());
        return R.fail(ResultCode.MEDIA_TYPE_NOT_SUPPORTED, ex.getMessage());
    }

    /**
     * 不接受的媒体类型
     */
    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public R<Void> handleError(HttpMediaTypeNotAcceptableException ex) {
        String message = ex.getMessage() + " " + StrUtil.join(StringPool.COMMA, ex.getSupportedMediaTypes());
        log.warn("[HttpMediaTypeNotAcceptableException] {}", message);
        return R.fail(ResultCode.MEDIA_TYPE_NOT_SUPPORTED, message);
    }
}
